<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions" class="m-table">
      <template #form="{ form }">
        <XForm style="padding: 16px 8px 8px" :fieldList="fieldList" :options="formOption" :formData="form"> </XForm>
      </template>

      <template #GoodsSlot="{ row }">
        <ExpandList :show-expand="row?.Items?.length > 1" :expand="row.expandStatus" @change="rendererView" :length="row?.Items?.length">
          <template #default="{ expand }">
            <div class="product-item" v-for="(item, index) in getRows(row, expand)" :key="`${item.sku}${index}`">
              <div class="border-[var(--base-border-color)] border-[1px] rounded-[4px] p-[7px] text-[14px] relative leading-[20px] w-[338px]">
                <div class="flex">
                  <div class="flex flex-1">
                    <div>
                      <VText title="系统SKU" :value="item.SKU" type="link" @click="onSku(item)" />
                    </div>
                    <div class="text-red ml-[8px]">x{{ item.ProductNum }}</div>
                  </div>

                  <div>({{ row.Currency }} {{ item.ProductPrice?.toFixed(2) }})</div>
                </div>

                <VText title="自定义SKU" :value="item.ClientSKU" />
                <VText title="渠道SKU" :value="item.SellerSKU" />
                <VText :value="item.ItemTitleCn" />
                <VText title="ASIN" :value="item.ASIN" />
              </div>
            </div>
          </template>
        </ExpandList>
      </template>
    </VTable>

    <AddRefund ref="addRefundRef" v-model="addVisible" @refresh="handleRefresh" :id="refundId" @close="handleClose" />

    <Address ref="AddressRef" />

    <Log ref="logRef" :api="refundLog"></Log>
  </VPage>
</template>

<script setup lang="jsx">
import { refundList, refundLog } from "./api"
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"

// 日志
import Log from "./components/log.vue"
const logRef = ref()

import ExpandList from "@/components/ExpandList/index.vue"

import Address from "./components/Address.vue"
const AddressRef = ref()
import { formOption, fieldList, tablecColumns, handleFunctions } from "./config.jsx"

import AddRefund from "@/views/user/irobotboxRefund/components/AddRefund/index.vue"
const addRefundRef = ref()
const addVisible = ref(false)
// 刷新列表
const handleRefresh = () => {
  // rows.value = []
  // refundId.value = ""
  addVisible.value = false
  // tableRef?.value.query()
  // getList()
}
const refundId = ref("")
const handleClose = () => {
  // refundId.value = ""
  addVisible.value = false
}

const handleEdit = (item) => {
  // refundId.value = item.id
  addVisible.value = true
  //
  addRefundRef.value.noCombined.type = "ClientOrderCode"
  addRefundRef.value.noCombined.value = item.ClientOrderCode
  console.log(addRefundRef.value)

  addRefundRef.value.handleGetOrderInfo()
}
const handleFunction = ref({
  openAddress: (row) => {
    console.log(row)
    AddressRef.value.open(row)
  },
  openAddRefund: (row) => {
    handleEdit(row)
  },
  openLog: (row) => {
    logRef.value.open({ order_code: row.OrderCode })
  },
})
onActivated(() => {
  // tableRef?.value?.updateScroll()
  nextTick(() => {}).then(() => {
    console.log("从新进入")
    getTable()
  })
})
const getTable = () => {
  const { type, value } = history.state || {}
  if (type) {
    tableRef?.value.setForm({ noRange: { type: "ClientOrderCode", value: value } })
    tableRef?.value.query()
  }
}

onMounted(async () => {
  nextTick(() => {
    handleFunctions.value = handleFunction.value
    getTable()
  })
})

import action from "@/utils/action.js"
import ProductApi from "@/components/SelectProduct/api"
const onSku = (item) => {
  ProductApi.query({ sku: [item.SKU] }).then((res) => {
    action.setGlobalState({
      changeMicoTabsPath: {
        path: "/goods/task/product/edit",
        type: "push",
        query: {
          type: "view",
          spuId: res.data?.[0].spu_id,
          sku: item.custom_sku,
        },
      },
    })
  })
}

const tableRef = ref()
// 渲染表格列
const rendererView = (e) => {}
const getRows = (rows, expand) => {
  rows.expandStatus = expand
  const { Items = [] } = rows || {}
  if (expand) return Items
  if (!Items?.length) return []
  if (Items.length > 0 && Items.length < 1) {
    return Items
  }
  if (!expand) {
    return Items?.slice(0, 1)
  }
}

const tableOptions = reactive({
  formConfig: {
    // save: "/oms/user/refund", // 必填，唯一
    data: {
      noRange: { type: "ClientOrderCode", value: "" },
    },
  },

  columns: [],
  scrollY: { enabled: false },

  pagerConfig: {
    pageSize: 10,
    pageSizes: [20, 50, 100],
    layouts: ["PrevPage", "Jump", "PageCount", "NextPage", , "Total"],
  },
  proxyConfig: {
    // autoLoad: !true, // 是否自动加载查询数据
    // props: {
    //   result: "data",
    //   total: "total",
    // },
    ajax: {
      query: async ({ page, form }) => {
        let param = {
          ...form,
          page: page.pageNum,
          pagesize: page.pageSize,
        }
        let res = await refundList(getForm(param))
        return res
      },
    },
  },
})

// const handleColumn = {
//   title: "操作",
//   width: 80,
//   fixed: "right",
//   slots: {
//     default: ({ row }) => {
//       return (
//         <div>
//           <el-button link type="primary" onClick={() => handleEdit(row)}>
//             编辑
//           </el-button>
//         </div>
//       )
//     },
//   },
// }
// { fixed: "left", type: "checkbox", width: 50 },
tableOptions.columns = [{ fixed: "left", type: "checkbox", width: 50 }, ...tablecColumns.value]

const getForm = (params) => {
  let keys = ["ClientOrderCode", "ClientUserAccount"]
  keys.forEach((key) => {
    params[key] = params[key] ? params[key] : ""
    params[key] = params[key]?.split("\n")?.filter((v) => !!v.trim())
    params[key] = params[key]?.map((v) => v.trim())
  })

  return params
}
</script>
<style lang="scss" scoped></style>
